#!/bin/bash

cd /home/<%= fetch(:user) %>/apps/<%= fetch(:application) %>/shared
curdate=$(date +"%m-%d-%y")
mkdir -p "backuping/version-$curdate"

zip -u -0 -r -s 1000 "backuping/version-$curdate/assets.zip" <% (fetch(:backupFolders) || []).each do |folder|%> <%= folder + ' ' %> <% end %>

adapter=$(cat config/database.yml | grep adapter | sed s/adapter://g | xargs)
if [ "$adapter" = "sqlite3" ]; then
  DATA_BASE_TYPE="<%=fetch(:stage)%>.sqlite3"
  cp "<%=fetch(:stage)%>.sqlite3" "backuping/version-$curdate/<%=fetch(:stage)%>.sqlite3"
fi
if [ "$adapter" = "mysql2" ]; then
DATA_BASE_TYPE="<%=fetch(:stage)%>.sql"
username=$(cat config/database.yml | grep username | sed s/username://g | xargs)
password=$(cat config/database.yml | grep password | sed s/password://g | xargs)
database=$(cat config/database.yml | grep database | sed s/database://g | xargs)
mysqldump --user="$username" --password="$password" $database > "backuping/version-$curdate/<%=fetch(:stage)%>.sql"
fi

COUNTER=5
until [  $COUNTER -lt 1 ]; do
    python drivesink.py upload "backuping" <%= fetch(:backupDestinationFolder) || "backups/firstdedic-server/" + fetch(:application)  %> >> log/backup.log 2>&1
    if [ $? -eq 0 ]; then
      COUNTER=0
    else
      COUNTER=$($COUNTER -1)
    fi
done

if [ $? -eq 0 ]; then
SIZE=$(du -sh backuping | awk '{print $1}')
curl -X POST -H 'Content-type: application/json' \
--data "{'attachments': [{'mrkdwn_in': ['text'],'text': 'Успешо создан бэкап для *<%= fetch(:application) %>*\n<% (fetch(:backupFolders) || []).each do |folder|%><%= "- " +folder + '\n' %><% end %>- $DATA_BASE_TYPE\nРазмер *$SIZE*','color': '#3AA3E3', 'title': 'Amazon Backup System'}]<%=", \'channel\': \'#{fetch(:slack_channel)}\' " if !fetch(:slack_channel).nil? %>}" \
<%= fetch(:slack_hook) %>
else
curl -X POST -H 'Content-type: application/json' \
--data "{'attachments': [{'mrkdwn_in': ['text'],'text': 'Произошла ошибка при создании бэкапа для *<%= fetch(:application) %>','color': '#FF0000', 'title': 'Amazon Backup System'}]<%=", \'channel\': \'#{fetch(:slack_channel)}\' " if !fetch(:slack_channel).nil? %>}" \
<%= fetch(:slack_hook) %>
fi

rm -rf backuping
